package com.dtw.ditouwang.utils;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.ParameterizedType;

public class SharedPreferencesUtil {
    private static final String KeyUserName = "KeyUserNames";
    private static final String KeyPassword = "KeyPassword";
    private static final String KeyLoginType = "KeyLoginType";
    private static SharedPreferencesUtil sharedPreferencesUtil;
    private SharedPreferences sharedPreferences;

    public enum LoginType{
        Null,Phone,Wechat
    }

    private SharedPreferencesUtil(Context context){
        sharedPreferences = context.getApplicationContext().getSharedPreferences(context.getPackageName().replace(".", ""), Context.MODE_PRIVATE);
    }

    public static SharedPreferencesUtil getInstance(Context context){
        if(sharedPreferencesUtil==null){
            sharedPreferencesUtil=new SharedPreferencesUtil(context);
        }
        return sharedPreferencesUtil;
    }

    public void setUserName(String userName){
        sharedPreferences.edit().putString(KeyUserName, userName).apply();
    }
    public String getUserName(){
        return sharedPreferences.getString(KeyUserName, null);
    }

    public void setUserPassword(String password){
        sharedPreferences.edit().putString(KeyPassword, password).apply();
    }

    public void setLoginType(LoginType type){
        sharedPreferences.edit().putInt(KeyLoginType,type.ordinal()).apply();
    }

    public LoginType getLoginType(){
        return LoginType.values()[sharedPreferences.getInt(KeyLoginType,0)];
    }

    public String getPassword(){
        return sharedPreferences.getString(KeyPassword, null);
    }

    public <T>void setBean(T bean){
        sharedPreferences.edit().putString(bean.getClass().getSimpleName(), new Gson().toJson(bean)).apply();
    }

    public <T>T getBean(Class<T> tClass){
        return new Gson().fromJson(sharedPreferences.getString(tClass.getSimpleName(),""),tClass);
    }

    public boolean isFirstIn(){
//        if(sharedPreferences.getBoolean("firstin",true)) {
//            sharedPreferences.edit().putBoolean("firstin", false).apply();
//            return true;
//        }
//        return false;
        return true;
    }
}
